import React, { useState, useEffect } from 'react';
import { Button, Table, Modal, message, Input } from 'antd';
import { SearchOutlined } from '@ant-design/icons';

const { Search } = Input;

const BookMg = () => {
    const [isModalVisible, setIsModalVisible] = useState(false);
    const [selectedBook, setSelectedBook] = useState(null);
    const [selectedRowKeys, setSelectedRowKeys] = useState([]);
    // 新增状态，控制选择框是否显示
    const [showSelection, setShowSelection] = useState(false);
    const [searchText, setSearchText] = useState('');
    const [searchedColumn, setSearchedColumn] = useState('');

    // 新增：点击外部隐藏选择框
    useEffect(() => {
        const handleClickOutside = (event) => {
            if (showSelection && !event.target.closest('.ant-btn')) {
                setShowSelection(false);
                setSelectedRowKeys([]);
            }
        };

        document.addEventListener('mousedown', handleClickOutside);

        return () => {
            document.removeEventListener('mousedown', handleClickOutside);
        };
    }, [showSelection]);

    const handleAdd = () => {
        message.info('添加图书功能待实现');
    };

    const handleDelete = () => {
        if (!showSelection) {
            // 第一次点击，显示选择框
            setShowSelection(true);
        } else {
            if (selectedRowKeys.length === 0) {
                // 没有勾选，再次点击删除，隐藏选择框
                setShowSelection(false);
                return;
            }
            message.success(`成功删除${selectedRowKeys.length}本图书`);
            setSelectedRowKeys([]);
            setShowSelection(false);
        }
    };

    const handleMore = (record) => {
        setSelectedBook(record);
        setIsModalVisible(true);
    };

    const handleSearch = (selectedKeys, confirm, dataIndex) => {
        confirm();
        setSearchText(selectedKeys[0]);
        setSearchedColumn(dataIndex);
    };

    const handleReset = (clearFilters) => {
        clearFilters();
        setSearchText('');
    };

    const getColumnSearchProps = (dataIndex) => ({filterDropdown: ({ setSelectedKeys, selectedKeys, confirm, clearFilters }) => (
            <div style={{ padding: 8 }}>
                <Search
                    placeholder={`搜索 ${dataIndex}`}
                    value={selectedKeys[0]}
                    onChange={(e) => setSelectedKeys(e.target.value ? [e.target.value] : [])}
                    onPressEnter={() => handleSearch(selectedKeys, confirm, dataIndex)}
                    style={{ width: 188, marginBottom: 8, display: 'block',height: 40}}
                />
                <Button
                    onClick={() => handleSearch(selectedKeys, confirm, dataIndex)}
                    icon={<SearchOutlined />}
                    size="small"
                    style={{ width: 90, marginRight: 8 }}
                >
                    搜索
                </Button>
                <Button onClick={() => handleReset(clearFilters)} size="small" style={{ width: 90 }}>
                    重置
                </Button>
            </div>
        ),
        filterIcon: (filtered) => (
            <SearchOutlined style={{ color: filtered ? '#1890ff' : undefined }} />
        ),
        onFilter: (value, record) =>
            record[dataIndex].toString().toLowerCase().includes(value.toLowerCase()),
        onFilterDropdownVisibleChange: (visible) => {
            if (visible) {
                // 原代码中 this.searchInput 未定义，这里暂时注释掉
                // setTimeout(() => this.searchInput.focus());
            }
        },
    });

    const rowSelection = showSelection ? {
        selectedRowKeys,
        onChange: (selectedKeys) => {
            setSelectedRowKeys(selectedKeys);
        },
    } : null;

    const columns = [
        { title: 'ID', dataIndex: 'id', key: 'id', ...getColumnSearchProps('id') },
        { title: '书名', dataIndex: 'bookName', key: 'bookName', ...getColumnSearchProps('bookName') },
        { title: 'ISBN', dataIndex: 'isbn', key: 'isbn', ...getColumnSearchProps('isbn') },
        { title: '入库时间', dataIndex: 'storageDate', key: 'storageDate', ...getColumnSearchProps('storageDate') },
        // 修改列名和 dataIndex
        { title: '作者', dataIndex: 'author', key: 'author', ...getColumnSearchProps('author') },
        // 修改列名和 dataIndex
        { title: '出版社', dataIndex: 'publisher', key: 'publisher', ...getColumnSearchProps('publisher') },
        { 
            title: '更多', 
            key: 'more', 
            render: (_, record) => ( 
                <a style={{ color: 'blue' }} onClick={() => handleMore(record)}>
                    更多
                </a>
            ),
        },
    ];

    const data = Array.from({ length: 100 }, (_, index) => {
        const storageDate = new Date();
        storageDate.setDate(storageDate.getDate() - Math.floor(Math.random() * 30));
        return {
            key: index,
            id: index + 1,
            bookName: `书籍${index + 1}`,
            isbn: `ISBN-${Math.floor(Math.random() * 1000000000)}`,
            storageDate: storageDate.toISOString().split('T')[0],
            // 修改字段名
            author: `作者${index + 1}`,
            // 修改字段名
            publisher: `出版社${String.fromCharCode(65 + Math.floor(Math.random() * 26))}-${Math.floor(Math.random() * 100)}`,
            // 新增库存和位置字段
            stock: Math.floor(Math.random() * 100),
            location: `书架${String.fromCharCode(65 + Math.floor(Math.random() * 26))}-${Math.floor(Math.random() * 100)}`,
        };
    });

    // 按入库时间从近到远排序
    const sortedData = [...data].sort((a, b) => {
        return new Date(b.storageDate) - new Date(a.storageDate);
    });

    // 过滤数据
    const filteredData = sortedData.filter((record) => {
        if (!searchText) return true;
        return record[searchedColumn].toString().toLowerCase().includes(searchText.toLowerCase());
    });

    return ( 
        <div>
            <div style={{ marginBottom: 16 }}>
                <Button onClick={handleAdd}>添加</Button>
                <Button 
                    style={{ marginLeft: 8, backgroundColor: (showSelection && selectedRowKeys.length > 0) ? '#ff4d4f' : '', borderColor: (showSelection && selectedRowKeys.length > 0) ? '#ff4d4f' : '', color: (showSelection && selectedRowKeys.length > 0) ? '#fff' : '' }} 
                    onClick={handleDelete}
                >
                    {showSelection ? '确认删除' : '删除'}
                </Button>
            </div>
            <Table 
                rowSelection={rowSelection}
                columns={columns} 
                dataSource={filteredData} 
                pagination={{ pageSize: 20 }} 
            />
            <Modal
                title="图书信息"
                visible={isModalVisible}
                onCancel={() => setIsModalVisible(false)}
                footer={null}
            >
                {selectedBook && ( 
                    <div>
                        <p>ID: {selectedBook.id}</p>
                        <p>书名: {selectedBook.bookName}</p>
                        <p>ISBN: {selectedBook.isbn}</p>
                        <p>入库时间: {selectedBook.storageDate}</p>
                        <p>作者: {selectedBook.author}</p>
                        <p>出版社: {selectedBook.publisher}</p>
                        {/* 新增库存和位置信息 */}
                        <p>库存: {selectedBook.stock}</p>
                        <p>位置: {selectedBook.location}</p>
                    </div>
                )}
            </Modal>
        </div>
    );
};

export default BookMg;